package com.example.tutorialmongodb.syncdata.service;

import com.example.tutorialmongodb.syncdata.model.UserLoginPromotionChannelEntity;
import com.mongodb.MongoException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * @author: cph
 * @date: 2021/10/26 17:44
 */
@Slf4j
@Service
public class MongoDBServiceImpl implements MongoDBService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void upsert(
            String userId,
            String tuiguangId,
            String generalizeId,
            String url,
            Timestamp updateTime) {
        try {
            log.info(
                    "MongoDB保存或更新获客渠道 入参: userId:[{}], tuiguangId:[{}], generalizeId:[{}], url:[{}], updateTime:[{}]",
                    userId,
                    tuiguangId,
                    generalizeId,
                    url,
                    updateTime);
            Query query =
                    new Query(Criteria.where("userId").is(userId).and("tuiguangId").is(tuiguangId));
            Update update =
                    new Update()
                            .set("generalizeId", generalizeId)
                            .set("url", url)
                            .set("updateTime", updateTime);
            mongoTemplate.upsert(query, update, UserLoginPromotionChannelEntity.class);
        } catch (MongoException e) {
            log.error("MongoDB保存或更新获客渠道异常", e);
        }
    }
}
